package com.phone.handle;

import com.phone.entity.Cash;
import com.phone.entity.Prize;
import com.phone.exception.ErrorOwneridException;
import com.phone.exception.NoBindingIdException;
import com.phone.exception.NotSufficientMoneyException;
import org.hibernate.HibernateException;
import org.hibernate.Session;

import java.util.Date;
import java.util.List;

/**
 * Created by tisen on 2017/7/5.
 */
public class PrizeHandle {
    private Session session;

    public PrizeHandle(Session session) {
        this.session = session;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public String save(String ownerid, String type ,String info) throws Exception {
        UserHandle userHandle = new UserHandle(session);
        if (userHandle.checkId(ownerid)) {
                Prize prize = new Prize();
                prize.setOwnerid(ownerid);
                prize.setType(type);
                prize.setInfo(info);
                prize.setDate(new Date());
                return (String) session.save(prize);
        } else {
            throw new ErrorOwneridException();
        }
    }

    public void url(String id,String url) throws Exception {
        Prize prize = session.get(Prize.class,id);
        if (prize == null)
            throw new NoBindingIdException();
        prize.setVideourl(url);
        session.update(prize);
    }

    public Prize get(String id) throws Exception {
        Prize prize = session.get(Prize.class, id);
        if (prize == null)
            throw new NoBindingIdException();
        return prize;
    }

    public void complete(String id) throws Exception {
        Prize prize = session.get(Prize.class, id);
        if (prize == null)
            throw new NoBindingIdException();
        prize.setComplete(true);
        prize.setCompletedate(new Date());
        session.update(prize);
    }

    public List<Prize> search(String ownerid) throws Exception {
        List<Prize>prizes = session.createQuery("from Prize where ownerid='" + ownerid + "'").list();
        if(prizes==null||prizes.isEmpty()){
            throw new ErrorOwneridException();
        }
        return prizes;
    }
}
